
import {computed} from 'vue'
import { useRouter, useRoute } from 'vue-router'
export const useLink=(props)=>{
  const router = useRouter()
  const linkUrl = computed(() => {
    const type = typeof props.to
    if (type !== 'string') {
      return null
    }
    if (props.to.includes('//')) {
      return props.to
    }
    
    if (router) {
      const current = useRoute()
      const route = router.resolve(props.to, current)
      return route ? route.href : props.to
    }
    return props.to
  })

  const handleOpenTo = () => {

    let to = props.to
    if (router) {
      const current = useRoute()
      const route = router.resolve(props.to, current)
      to = route ? route.href : props.to
    }
    if (typeof props.to === 'string') return // 会跳转两次 // todo Vue3这里不跳2次，待验证
    window.open(to)
  }
  const handleClick= (new_window = false)=> {
    // const router = this.$router;
  
    if (new_window) {
      handleOpenTo();
    } else {
      if (router) {
        if ((typeof props.to === 'string') && props.to.includes('//')) {
          window.location.href = props.to;
        } else {
          props.replace ? router.replace(props.to, () => {}) : router.push(props.to, () => {});
        }
      } else {
        window.location.href = props.to;
      }
    }
  }
  
  const handleCheckClick = (event, new_window = false) => {
    if (props.to) {
      if (props.target === '_blank') {
        handleOpenTo()
        return false
      } else {
        event.preventDefault()
        handleClick(new_window)
      }
    }
  }

  return{
    handleCheckClick,
    linkUrl
  }
}